import React, { useEffect } from 'react';
import wx from 'weixin-js-sdk';

const SharePage = () => {
  useEffect(() => {
    // 初始化微信JS-SDK
    wx.config({
      // 配置信息
      debug: false,
      appId: 'your_app_id',
      timestamp: 'your_timestamp',
      nonceStr: 'your_nonceStr',
      signature: 'your_signature',
      jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage'],
    });

    // 获取当前页面的URL
    const url = window.location.href.split('#')[0];

    // 设置微信分享config
    wx.ready(() => {
      wx.onMenuShareTimeline({
        title: '分享标题',
        link: url,
        imgUrl: '分享缩略图',
        success: () => {
          // 分享成功回调
        },
        cancel: () => {
          // 分享取消回调
        },
      });

      wx.onMenuShareAppMessage({
        title: '分享标题',
        desc: '分享描述',
        link: url,
        imgUrl: '分享缩略图',
        success: () => {
          // 分享成功回调
        },
        cancel: () => {
          // 分享取消回调
        },
      });
    });
  }, []);

  const handleShare = () => {
    // 点击分享按钮时调用微信分享接口
    wx.ready(() => {
      wx.showMenuItems({
        menuList: ['menuItem:share:timeline', 'menuItem:share:appMessage'],
        success: () => {
          wx.hideMenuItems({
            menuList: ['menuItem:share:qq', 'menuItem:share:weiboApp', 'menuItem:share:facebook', 'menuItem:share:QZone', 'menuItem:copyUrl', 'menuItem:openWithSafari', 'menuItem:openWithQQBrowser', 'menuItem:share:email'],
            success: () => {
              wx.onMenuShareTimeline({
                title: '分享标题',
                link: window.location.href.split('#')[0],
                imgUrl: '分享缩略图',
                success: () => {
                  // 分享成功回调
                },
                cancel: () => {
                  // 分享取消回调
                },
              });

              wx.onMenuShareAppMessage({
                title: '分享标题',
                desc: '分享描述',
                link: window.location.href.split('#')[0],
                imgUrl: '分享缩略图',
                success: () => {
                  // 分享成功回调
                },
                cancel: () => {
                  // 分享取消回调
                },
              });
            },
          });
        },
      });
    });
  };

  return (
    <div>
      <button onClick={handleShare}>分享</button>
    </div>
  );
};

export default SharePage;